<template>
  <div class="home">
    <!-- 添加用户信息和欢迎按钮 -->
    <div class="auth-container">
      <template v-if="!isLoggedIn">
        <div class="auth-buttons">
          <el-button 
            type="primary" 
            plain 
            class="auth-btn login-btn" 
            @click="goToLogin"
          >
            登录
          </el-button>
          <el-button 
            type="primary" 
            class="auth-btn register-btn" 
            @click="goToRegister"
          >
            注册
          </el-button>
        </div>
      </template>
      <template v-else>
        <div class="user-info">
          <el-popover
            placement="bottom"
            :width="200"
            trigger="hover"
            popper-class="user-info-popover"
          >
            <template #reference>
              <el-avatar 
                :size="40" 
                :src="getAvatarUrl(userInfo.avatar)" 
                class="user-avatar"
              >
                {{ userInfo.fullName?.charAt(0) }}
              </el-avatar>
            </template>
            <div class="user-detail">
              <h4>{{ userInfo.fullName }}</h4>
              <p v-if="userInfo.email">
                <el-icon><Message /></el-icon>
                {{ userInfo.email }}
              </p>
              <p v-if="userInfo.phone">
                <el-icon><Phone /></el-icon>
                {{ userInfo.phone }}
              </p>
            </div>
          </el-popover>
          <span class="user-name">{{ userInfo.fullName }}</span>
          <el-button 
            type="primary" 
            class="welcome-btn" 
            @click="handleWelcome"
          >
            欢迎进入
          </el-button>
          <el-button 
            type="danger" 
            plain 
            @click="handleLogout"
          >
            退出登录
          </el-button>
        </div>
      </template>
    </div>

    <div class="hero-section">
      <div class="hero-content">
        <div class="logo-container">
          <img src="http://127.0.0.1:9010/conference/conference_logo.jpg" alt="会议管理系统" class="logo-image">
        </div>
        <h1 class="hero-title">数字会务管理系统</h1>
        <p class="hero-subtitle">高效便捷的会议管理解决方案</p>
      </div>
    </div>

    <div class="content-wrapper">
      <!-- 功能特点卡片 -->
      <div class="features-section">
        <h2 class="section-title">核心功能</h2>
        <el-row :gutter="32">
          <el-col :xs="24" :sm="12" :md="8" v-for="(feature, index) in features" :key="index">
            <div class="feature-card">
              <div class="feature-icon">
                <component :is="feature.icon" />
              </div>
              <h3 class="feature-title">{{ feature.title }}</h3>
              <p class="feature-description">{{ feature.description }}</p>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 系统介绍部分 -->
      <div class="intro-section">
        <div class="intro-content">
          <h2 class="section-title">关于系统</h2>
          <p class="intro-text">会议管理系统是一个专业的会议管理平台，为用户提供全方位的会议管理服务。</p>
          <div class="feature-grid">
            <div class="feature-item" v-for="(item, index) in introFeatures" :key="index">
              <component :is="item.icon" :class="item.iconClass" />
              <span>{{ item.text }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 快速入门指引 -->
      <div class="steps-section">
        <h2 class="section-title">快速入门</h2>
        <el-steps :active="1" finish-status="success" class="custom-steps">
          <el-step title="创建会议" description="快速创建您的第一个会议" />
          <el-step title="场地安排" description="灵活设置会议场地与座位" />
          <el-step title="日程规划" description="便捷管理会议日程安排" />
          <el-step title="发布会议" description="一键发布会议信息" />
        </el-steps>
      </div>

      <el-row :gutter="20" class="conference-list">
        <el-col v-for="conference in conferences" :key="conference.id" :xs="24" :sm="12" :md="8" :lg="6">
          <el-card class="conference-card" shadow="hover">
            <h3>{{ conference.title }}</h3>
            <p class="location"><i class="el-icon-location"></i> {{ conference.location }}</p>
            <p class="time"><i class="el-icon-time"></i> {{ formatDateTime(conference.startTime) }}</p>
            <div class="status-tag">
              <el-tag :type="getStatusType(conference.status)">
                {{ getStatusText(conference.status) }}
              </el-tag>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, inject, watch } from 'vue'
import request from '@/utils/request'
import { useRouter } from 'vue-router'
import {
  Calendar,
  Location,
  Timer,
  Document,
  Setting,
  DataAnalysis,
  Message,
  Phone
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const conferences = ref([])
const isLoggedIn = ref(false)

// 注入全局用户信息
const userInfo = inject('userInfo')
const updateUserInfo = inject('updateUserInfo')

// 添加缺失的数据
const features = ref([
  {
    icon: Calendar,
    title: '会议日程管理',
    description: '灵活创建和管理会议日程，自动发送提醒，确保与会者准时参加。'
  },
  {
    icon: Location,
    title: '场地资源管理',
    description: '高效分配和管理会议场地资源，避免冲突，优化场地利用率。'
  },
  {
    icon: Document,
    title: '文档资料管理',
    description: '集中管理会议相关文档资料，参会人员可随时查阅和下载。'
  },
  {
    icon: Setting,
    title: '参会人员管理',
    description: '便捷管理参会人员信息，支持批量导入，自动生成签到表。'
  },
  {
    icon: DataAnalysis,
    title: '数据统计分析',
    description: '全面统计分析会议数据，生成直观的图表，辅助决策。'
  },
  {
    icon: Timer,
    title: '签到与考勤',
    description: '支持扫码签到，实时统计出勤情况，确保会议顺利进行。'
  }
])

const introFeatures = ref([
  { icon: Calendar, iconClass: 'icon-blue', text: '个性化会议定制' },
  { icon: Location, iconClass: 'icon-green', text: '智能会议室分配' },
  { icon: Timer, iconClass: 'icon-orange', text: '自动日程提醒' },
  { icon: Setting, iconClass: 'icon-purple', text: '数据安全保障' },
  { icon: DataAnalysis, iconClass: 'icon-red', text: '效率提升50%' }
])

const getStatusText = (status) => {
  const statusMap = {
    'upcoming': '即将开始',
    'ongoing': '进行中',
    'completed': '已结束',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
  const statusMap = {
    'upcoming': 'primary',
    'ongoing': 'success',
    'completed': 'info',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

const formatDateTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

const fetchConferences = async () => {
  try {
    const response = await request({
      url: '/api/conferences',
      method: 'get',
      params: {
        page: 0,  // 后端分页从0开始
        size: 8,
        status: 'PUBLISHED'  // 只获取已发布的会议
      }
    })
    
    console.log('首页会议列表响应:', response)
    
    if (response && response.content) {
      conferences.value = response.content.slice(0, 8)  // 只显示前8个会议
    } else {
      console.warn('会议列表数据格式不符合预期:', response)
      conferences.value = []
    }
  } catch (error) {
    console.error('获取会议列表失败:', error)
    conferences.value = []
  }
}

// 检查登录状态
const checkLoginStatus = () => {
  const token = localStorage.getItem('token')
  const storedUserInfo = localStorage.getItem('userInfo')
  
  if (token && storedUserInfo) {
    try {
      const parsedUserInfo = JSON.parse(storedUserInfo)
      isLoggedIn.value = true
      // 更新全局用户信息
      updateUserInfo(parsedUserInfo)
    } catch (error) {
      console.error('解析用户信息失败:', error)
      isLoggedIn.value = false
      updateUserInfo(null)
      // 清除无效的存储数据
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  } else {
    isLoggedIn.value = false
    updateUserInfo(null)
  }
}

// 添加路由监听
watch(
  () => router.currentRoute.value.path,
  () => {
    checkLoginStatus()
  }
)

// 处理欢迎按钮点击
const handleWelcome = () => {
  const permissionId = userInfo.value.permissionId
  if (permissionId === 1) {
    // 会议组织者
    router.push('/conferences')
  } else {
    // 参会人员
    router.push('/dashboard')
  }
}

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
  isLoggedIn.value = false
  updateUserInfo(null)
  ElMessage.success('退出登录成功')
  router.push('/login')
}

// 导航方法
const goToLogin = () => {
  router.push('/login')
}

const goToRegister = () => {
  router.push('/register')
}

// 在 setup 中添加 getAvatarUrl 方法
const getAvatarUrl = (avatar) => {
  if (!avatar) return ''
  // 如果是完整的URL（以http或https开头），直接返回
  if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
    return avatar
  }
  // 否则，拼接基础URL
  return `http://127.0.0.1:9010/conference${avatar.startsWith('/') ? '' : '/'}${avatar}`
}

onMounted(() => {
  checkLoginStatus()
  fetchConferences()
})
</script>

<style scoped>
.home {
  min-height: 100vh;
  background: linear-gradient(135deg, #f6f8fc 0%, #e9ecf4 100%);
  position: relative;
}

.auth-container {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 100;
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.auth-container:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
}

.auth-buttons {
  display: flex;
  gap: 12px;
}

.auth-btn {
  min-width: 90px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 3px solid rgba(255, 255, 255, 0.8);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.user-avatar:hover {
  transform: scale(1.1) rotate(5deg);
  border-color: #1890ff;
}

.user-name {
  font-weight: 600;
  color: #1f2937;
  font-size: 1.1em;
}

.welcome-btn {
  margin: 0 8px;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  border: none;
  color: white;
  font-weight: 500;
  padding: 8px 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.welcome-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.hero-section {
  min-height: 70vh;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 60px 24px;
  position: relative;
  overflow: hidden;
}

.hero-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="50" cy="50" r="40" fill="none" stroke="white" stroke-width="0.5" stroke-opacity="0.1"/></svg>') center/50px 50px repeat;
  opacity: 0.1;
}

.hero-content {
  max-width: 1000px;
  padding: 40px;
  position: relative;
  z-index: 1;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  animation: fadeInUp 1s ease-out;
}

.logo-container {
  margin-bottom: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.logo-container::after {
  content: '';
  position: absolute;
  bottom: -16px;
  left: 50%;
  transform: translateX(-50%);
  width: 60%;
  height: 2px;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.5), transparent);
}

.logo-image {
  width: 400px;
  height: auto;
  object-fit: contain;
  border-radius: 20px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  transition: transform 0.3s ease;
  animation: logoFloat 3s ease-in-out infinite;
  background: rgba(255, 255, 255, 0.95);
  padding: 20px;
}

.logo-image:hover {
  transform: scale(1.02);
}

.hero-title {
  font-size: 48px;
  font-weight: 700;
  margin: 32px 0 20px;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  line-height: 1.2;
  letter-spacing: -0.02em;
}

.hero-subtitle {
  font-size: 24px;
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
  line-height: 1.6;
  font-weight: 500;
}

@keyframes logoFloat {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 60px 40px;
  position: relative;
}

.section-title {
  font-size: 32px;
  color: #1f2937;
  margin-bottom: 40px;
  text-align: center;
  font-weight: 700;
  position: relative;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 4px;
  background: linear-gradient(90deg, #1890ff, #36cfc9);
  border-radius: 2px;
}

.features-section {
  padding: 40px 0;
}

.feature-card {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 30px;
  height: 100%;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.04);
}

.feature-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 16px 32px rgba(0, 0, 0, 0.08);
  border-color: rgba(24, 144, 255, 0.2);
}

.feature-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24px;
  background: linear-gradient(135deg, rgba(24, 144, 255, 0.1) 0%, rgba(54, 207, 201, 0.1) 100%);
  color: #1890ff;
  transition: all 0.3s ease;
  font-size: 32px;
}

.feature-card:hover .feature-icon {
  transform: scale(1.1);
  background: linear-gradient(135deg, rgba(24, 144, 255, 0.2) 0%, rgba(54, 207, 201, 0.2) 100%);
}

.feature-title {
  font-size: 24px;
  color: #1f2937;
  margin-bottom: 16px;
  font-weight: 600;
}

.feature-description {
  color: #4b5563;
  font-size: 16px;
  line-height: 1.8;
  margin: 0;
}

.intro-section {
  padding: 80px 0;
  background: rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(10px);
  border-radius: 32px;
  margin: 40px 0;
}

.intro-content {
  max-width: 1000px;
  margin: 0 auto;
  text-align: center;
}

.intro-text {
  font-size: 18px;
  color: #4b5563;
  line-height: 1.8;
  margin-bottom: 48px;
}

.feature-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 32px;
  margin-top: 48px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.feature-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.icon-blue { color: #1890ff; font-size: 24px; }
.icon-green { color: #52c41a; font-size: 24px; }
.icon-orange { color: #faad14; font-size: 24px; }
.icon-purple { color: #722ed1; font-size: 24px; }
.icon-red { color: #f5222d; font-size: 24px; }

.custom-steps {
  max-width: 1000px;
  margin: 0 auto;
  padding: 40px 0;
}

.conference-list {
  margin-top: 40px;
}

.conference-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 20px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.conference-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.conference-card h3 {
  font-size: 20px;
  color: #1f2937;
  margin: 0 0 16px;
  font-weight: 600;
}

.location, .time {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #4b5563;
  margin: 8px 0;
  font-size: 14px;
}

.status-tag {
  margin-top: 16px;
}

.user-detail {
  padding: 8px;
}

.user-detail h4 {
  margin: 0 0 12px 0;
  color: #1f2937;
  font-size: 16px;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 8px;
}

.user-detail p {
  margin: 8px 0;
  color: #4b5563;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-detail .el-icon {
  font-size: 16px;
  color: #1890ff;
}

:deep(.el-popover.user-info-popover) {
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

@media screen and (max-width: 768px) {
  .auth-container {
    position: relative;
    top: 0;
    right: 0;
    margin: 20px;
    width: calc(100% - 40px);
  }

  .logo-image {
    width: 280px;
    padding: 16px;
  }

  .hero-section {
    padding: 40px 20px;
  }

  .hero-content {
    padding: 24px;
  }

  .hero-title {
    font-size: 36px;
    margin: 24px 0 16px;
  }

  .hero-subtitle {
    font-size: 18px;
  }

  .content-wrapper {
    padding: 40px 20px;
  }

  .section-title {
    font-size: 28px;
  }

  .feature-card {
    padding: 24px;
  }

  .feature-title {
    font-size: 20px;
  }

  .intro-section {
    padding: 40px 20px;
    margin: 20px 0;
  }

  .feature-grid {
    gap: 20px;
  }

  .user-info {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .welcome-btn {
    width: 100%;
    margin: 12px 0;
  }
}

@media screen and (max-width: 480px) {
  .hero-section {
    padding: 32px 16px;
  }

  .hero-content {
    padding: 20px;
  }

  .logo-image {
    width: 220px;
    padding: 12px;
  }

  .hero-title {
    font-size: 28px;
    margin: 20px 0 12px;
  }

  .hero-subtitle {
    font-size: 16px;
  }

  .auth-buttons {
    flex-direction: column;
    width: 100%;
  }

  .auth-btn {
    width: 100%;
  }
}
</style> 